R markdown creates interactive reports from R code. This post provides a few tips I use on a daily basis to improve the appearance of output documents. In any case, an unavoidable resource is the Rstudio documentation.

1 Text formating


R markdown allows to easily format your text. You can add links, write in bold or italic. This is very well explained in the Rstudio cheatsheet.

Here is the code I used to make this paragraph:

R markdown allows to easily format your text. You can add [links](www.r-graph-gallery.com), write in **bold** or *italic*. This is very well explained in the [Rstudio cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf).

2 Horizontal lines


Add an horizontal line by adding 3 stars:

***

3 Chapter auto numbering


Header of level 1, 2, 3 are set using #, ## and ###. You can auto number your chapters using this option in the header:

---
title: "Your title"
output: 
  html_document:
    number_sections: TRUE
---

# Title
## A subtitle
## Another subtitle

# Another title

4 Skip a line


I really like to add spaces in my document to give it a more uncluttered look. This is done using the <br> command. This .rmd code:

A first sentence
<br><br><br><br>
A seconde sentence

will give this htmloutput:


A first sentence



A seconde sentence


5 Center an image


To center an image, use this code:

<center>
![FigName](logo_r_graph_gallery.jpg)
</center>
Here is the result
FigName

7 Add space before title


I find it pleasant to have a bit of space before starting a new chapter. You can use a <br> before each header. A more convenient way is to add some margin in your CSS. Create a style.css file:

h1, .h1, h2, .h2, h3, .h3 {
    margin-top: 84px;
}

A rmd document that takes into account this .css file:

---
title: "A document with a CSS included"
output:
  html_document:
    css: style.css
---

A title will follow, but with a lot of space before it

# Title 1

content of part 1

# Title 2

content of part 2

The document you are reading uses this css. See the separation between chapters.

8 Add caption to your figures


Specify the caption of your figure in the chunk header. Example:

{r, fig.align="center", fig.width=6, fig.height=6, fig.cap="Figure: Here is a really important caption."}
library(tidyverse)
mpg %>%
  ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) + 
    geom_boxplot() +
    xlab("class") +
    theme(legend.position="none")
Figure: Here is a really important caption.

Figure: Here is a really important caption.

9 Custom caption


Change the black default caption using CSS. Adding this code in your style.css file.

<style>
p.caption {
  font-size: 0.9em;
  font-style: italic;
  color: grey;
  margin-right: 10%;
  margin-left: 10%;  
  text-align: justify;
}
</style>
file will give this result:
Figure: Here is a really important caption, customized to be grey and in italic.

Figure: Here is a really important caption, customized to be grey and in italic.

10 Insert equations


Insert equation using Latex formating:

\(A = (\pi * \lambda \times r^{4}) / \alpha\)

Delimit Latex syntax with $

$A = (\pi * \lambda \times r^{4}) / \alpha $

11 2 figures in 2 columns {#2columns}


You can display 2 plots one beside each other. Add out.width=c('50%', '50%'), fig.show='hold' to your chunk header. Something like:

``{r out.width=c('50%', '50%'), fig.show='hold'}
boxplot(1:10)
plot(rnorm(10))
`

12 Use buttons or tabs for sub-chapters


Save space in your document using buttons or tabs for sub chapters. Result can look like this:

12.1 First

content of sub-chapter #1




Here is the code used to create this section:

# Use buttons or tabs for sub-chapters {.tabset .tabset-fade .tabset-pills}
***
Save space in your document using buttons or tabs for sub chapters. Add this code at the end of your title:

## First
A first section

## Second
content of sub-chapter #2

## Third
content of sub-chapter #3

Note that I’ve also custom the buttons using this CSS:

.btn {
    border-width: 0 0px 0px 0px;
    font-weight: normal;
    text-transform: ;
}
.btn-default {
    color: #2ecc71;
    background-color: #ffffff;
    border-color: #ffffff;
}

12.2 Second

content of sub-chapter #2

12.3 Third

content of sub-chapter #3

13 Use DT for tables


The DT library is my favourite option to display tables in your document. It allows to:

Here is an example with the options I use most of the time:

library(DT)
datatable(mtcars, rownames = FALSE, filter="top", options = list(pageLength = 5, scrollX=T) )

14 Hide code


If you share your code with somebody who’s more focus on results than code, or if your code chunks are very long, you probably want to hide the code, but still allow the reader to consult it if necessary. This is possible by modifying the YAML header of your document:

output:
  html_document:
    code_folding: "hide"

Your code chunks will be hidden in the output, but a small ‘code’ button will be available to display it if necessary.

15 Highlight a piece of text


You can apply some css to a specific part of your document. Here is an example where I change the background color of a small part. Handy to highlight conclusions at the end of your document.

Code:

<style>
div.blue { background-color:#e6f0ff; border-radius: 5px; padding: 20px;}
</style>
<div class = "blue">

- This is my first conclusion
- This is my second conclusion

</div>
Will give:
  • This is my first conclusion
  • This is my second conclusion

16 Use parallax


Since R Markdown can output an html document, it is possible to apply whatever techniques used in common website. It is thus possible to set a header with a background image in parallax. See an example online here. Here is a glimpse of how it looks like:

gif

gif

You need to custom the css and the header.html files of your document. See the code provided in the corresponding github repository.

17 Cache code


It is possible to cache a specific chunk adding cache=TRUE in its header. You can also cash the whole document adding knitr::opts_chunk$set(cache=TRUE) in a chunk at the begining of the document.

Use this option with care, I strongly advise to read this document by Yihui Xie on this topic.

21 Use interactive graphics


R allows to build any type of interactive graphic. My favourite library is plotly that will turn any of your ggplot2 graphic interactive in one supplementary line of code. Try to hover points, to select a zone, to click on the legend.

library(ggplot2)
library(plotly)
library(gapminder)
 
p <- gapminder %>%
  filter(year==1977) %>%
  ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
  geom_point() +
  scale_x_log10() +
  theme_bw()
 
ggplotly(p)

22 Use a theme


You can use any of the bootswatch theme to automatically custom the font and general appearance of your document. You can also control the syntax highlighting style. See the possibilty here. Here is how to call these options in the YAML header:

title: "your title"
output:
  html_document:
    theme: sandstone
    highlight: tango

23 Use a template


Customize the document appearance using a template. Two packages offer several templates:


24 Share it online


Display your html online using github. Follow these steps:

An attempt to illustrate it with a few screenshots:

25 Compile several in a website


Explanation in the R Markdown Websites section of the R Markdown documentation. Note that this website is render using this technic. To run a basic example:

library(rmarkdown)
rmarkdown::render_site()

Note that you can go further using the blogdown package to generate static websites based on R Markdown and Hugo. This allows to build awesome websites only with R. It is used by a huge number of R blogs now.

26 Create template


If you often use the same kind of customization you probably want to create your own .rmd template. A good starting point is the Rstudio documentation.

This document is produced using my personal template: epuRate. I just custom a bit the CSS, added an header and a footer, and created a skeleton with tips I often use. An easy solution to create your template can be to fork / download this repo and apply your own style instead of mine.

27 Add a session info


It is a good practice to add a session info at the end of your document. It will increase reproducibility and costs only one line of code

sessionInfo()
## R version 3.4.1 (2017-06-30)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS Sierra 10.12.6
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] bindrcpp_0.2       gapminder_0.3.0    plotly_4.7.1      
##  [4] DT_0.2             forcats_0.3.0      stringr_1.3.0     
##  [7] dplyr_0.7.4        purrr_0.2.4        readr_1.1.1       
## [10] tidyr_0.8.0        tibble_1.4.2       ggplot2_2.2.1.9000
## [13] tidyverse_1.2.1    rmarkdown_1.9      epuRate_0.1       
## 
## loaded via a namespace (and not attached):
##  [1] reshape2_1.4.3      haven_1.1.0         lattice_0.20-35    
##  [4] colorspace_1.3-2    viridisLite_0.3.0   htmltools_0.3.6    
##  [7] yaml_2.1.18         rlang_0.2.0.9001    pillar_1.1.0       
## [10] foreign_0.8-69      glue_1.2.0          withr_2.1.2        
## [13] modelr_0.1.1        readxl_1.0.0        bindr_0.1          
## [16] plyr_1.8.4          munsell_0.4.3       gtable_0.2.0       
## [19] cellranger_1.1.0    rvest_0.3.2         htmlwidgets_1.2    
## [22] psych_1.7.8         evaluate_0.10.1     labeling_0.3       
## [25] knitr_1.20.1        httpuv_1.3.5        crosstalk_1.0.0    
## [28] parallel_3.4.1      highr_0.6           broom_0.4.2        
## [31] Rcpp_0.12.16        xtable_1.8-2        scales_0.5.0.9000  
## [34] backports_1.1.2     jsonlite_1.5        mime_0.5           
## [37] mnormt_1.5-5        hms_0.3             digest_0.6.15      
## [40] stringi_1.1.7       shiny_1.0.5         grid_3.4.1         
## [43] rprojroot_1.3-2     cli_1.0.0           tools_3.4.1        
## [46] magrittr_1.5        lazyeval_0.2.1      crayon_1.3.4       
## [49] pkgconfig_2.0.1     data.table_1.10.4-3 xml2_1.2.0         
## [52] lubridate_1.7.1     assertthat_0.2.0    httr_1.3.1         
## [55] rstudioapi_0.7      R6_2.2.2            nlme_3.1-131       
## [58] compiler_3.4.1

28 References


29 Feedback


This document provides a few tips I often use in my documents. I hope it can help. If you know any other tip I should add, please send me an email to paste("yan.holtz.data", "gmail.com", sep="""), or suggest it via the associated github repository.

This page is linked with the R graph gallery and you can also reach me on twitter!

 

A work by Yan Holtz

Yan.holtz.data@gmail.com